<?php

namespace app\admin\controller;

use app\common\model\Member;
use app\common\model\MemberPackages;
use app\common\model\Packages;
use app\common\model\UcenterMember;
use think\Db;
use app\common\api\controller\Bonus;
use app\common\api\controller\User as UserApi;
use app\common\api\controller\Error;
use think\Validate;


class User extends Home
{
    /**
     * 会员注册
     */
    public function registuser()
    {
        if (!config('USER_ALLOW_REGISTER')) {
            $this->error('注册已关闭');
        }

//        $info['usernumber'] = self::getUsernumber('jh');
        $info['tuijiannumber'] = Db('member')->where('status', 1)->order('uid asc')->value('usernumber');
//        $info['billcenternumber'] = $this->getServercenter($info['tuijiannumber']);

        $xm = xm2arr();
        $xs = xs2arr();
        $name = $xs[rand(0, 437)] . $xm[rand(0, 37)];
        $table = Db('member')->find();
        $this->assign('table', $table);
        $this->assign('userinfo', $info);
        $this->assign('allow_bank', config('ALLOW_BANK'));
        $this->assign('title', '会员注册');
        return $this->fetch();
    }

    /**
     * Notes:会员列表
     * User: Administrator
     * Date: 2023/8/31
     * Time: 9:47
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function userList()
    {
        $where = $this->getMap('active_time');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');
        $type = input('type', 1);
        $status = input('status', -2);
        $package_id = input('package_id', -2);
        if (!empty($usernumber)) {
            switch ($type) {
                case 1:
                    $map['usernumber'] = $usernumber;
                    break;
                case 2:
                    $map['realname'] = $usernumber;
                    break;
                case 3:
                    $map['m.mobile'] = $usernumber;
                    break;
            }
        }

        if ($status > -2) {
            $map['m.status'] = $maps['status'] = $status;
        }

        if ($package_id > -2) {
            $map['package_id'] = $maps['package_id'] = $package_id;
        }

        $list = Db('member')->alias('m')->join('zx_ucenter_member u', 'm.uid = u.id')->where($map)->order('id desc')->paginate(20, false, ['query' => $maps]);

        $page = $list->render();
        $list = $list->toArray();
        foreach ($list['data'] as &$v) {
            if ($v['area']) {
                $v['area'] = $this->getAddress($v['area']);
            }
            $v['package_name'] = $v['package_id'] > 0 ? Packages::where('id', $v['package_id'])->value('name') : '无';
            $v['start_sign_time'] = $v['start_sign_time'] > 0 ? date('Y-m-d', $v['start_sign_time']) : '未签到';
        }
        $this->assign('_list', $list['data']);
        $this->assign('page', $page);

        $packages = Packages::order('id asc')->column('name', 'id');

        $packages['-2'] = '全部';
        ksort($packages);

        /*追加查询条件*/
        $arr = array(
            array(
                'type' => 'select',
                'name' => 'type',
                'option' => array(
                    '1' => '会员账号',
                    '2' => '会员姓名',
                    '3' => '手机号码',
                ),
                'value' => $type,
                'inputid' => '',
                'readonly' => '',
            ),
            array(
                'type' => 'input',
                'name' => 'usernumber',
                'title' => '请输入会员账号等有效信息',
                'value' => $usernumber,
                'inputid' => '',
                'readonly' => '',
            ),

            array(
                'type' => 'select',
                'name' => 'package_id',
                'option' => $packages,
                'value' => $package_id,
                'inputid' => '',
                'readonly' => '',
            ),
            array(
                'type' => 'select',
                'name' => 'status',
                'option' => array(
                    '-2' => '全部',
                    '-1' => '冻结',
                    '1' => '未认证',
                    '2' => '待审核',
                    '3' => '已认证',
                ),
                'value' => $status,
                'inputid' => '',
                'readonly' => '',
            )
        );
        $this->searchCondition($maps, $arr);

        $this->assign('email', self::$adminInfo['email']);
//        $this->assign('search', url('userIndexd'));
        $this->assign('title', '会员列表');
        return $this->fetch('userindex');
    }


    public function userIndexd()
    {
        $where = $this->getMap('reg_time');
        $map = $where['map'];
        $status = input('status', -2);
        if ($status >= -1) {
            $map['m.status'] = $status;
        }
        $list = Db('member')->alias('m')->join('zx_ucenter_member u', 'm.uid = u.id')->where($map)->order('reg_time desc')->select();
        $title = "会员列表";
        $a = array(
            array('usernumber', '会员编号'),
            array('realname', '会员姓名'),
            array('userrank', '级别'),
            array('mobile', '手机号码'),
            array('hasbill', HASBILL),
            array('hasmoney', HASMONEY),
            array('hasfund', HASFUND),
            array('tuijiannumber', '推荐人'),
            array('reg_time', '注册时间'),
            array('active_time', '激活时间'),
            array('status', '会员状态'),
        );
        foreach ($list as $k => &$v) {
            $v['userrank'] = strip_tags(get_userrank($v['userrank']));
            $v['reg_time'] = date('Y-m-d H:i:s', $v['reg_time']);

            if ($v['active_time']) {
                $v['active_time'] = date('Y-m-d H:i:s', $v['active_time']);
            } else {
                $v['active_time'] = '尚未激活';
            }

            $v['status'] = strip_tags(get_status($v['status']));
        }

        exportExcel($title, $a, $list);
    }

    /**
     * 认证审核
     */
    public function authAudit()
    {
        $uid = input('uid');
        $memberModel = Member::find($uid);
        if ($memberModel->status != 2) {
            $this->error('不可审核！');
        }
        $ucenterModel = UcenterMember::find($uid);
        $type = input('type', 1);
        switch ($type) {
            case 1:
                // 同意
                Db::startTrans();
                try {
                    $packageInfo = Packages::order('id asc')->find();

                    $memberModel->package_id = $packageInfo->id;
                    $memberModel->status = 3;
                    $memberModel->save();

                    $ucenterModel->status = 3;
                    $ucenterModel->save();

                    $per_output = round($packageInfo->product / $packageInfo->min_days, 4);

                    $memberPackagesModel = new MemberPackages();
                    $memberPackagesModel->uid = $uid;
                    $memberPackagesModel->package_id = $packageInfo->id;
                    $memberPackagesModel->total_days = $packageInfo->min_days;
                    $memberPackagesModel->rank = 1;
                    $memberPackagesModel->per_output = $per_output;

                    $memberPackagesModel->save();
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $bonus = new Bonus();
//                $bonus->bonusRecom($uid, $packageInfo->cost);//推荐奖
                $bonus->addAchievement($uid, $packageInfo->cost);//团队增加成长值
                $bonus->updateRank($uid);// 团队升级

                break;

            case 2:
                // 拒绝
                Db::startTrans();
                try {
                    $memberModel->status = 1;
                    $memberModel->save();

                    $ucenterModel->status = 1;
                    $ucenterModel->save();

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                break;
        }

        $this->success('审核成功！');
    }

    /**
     * Notes:会员签到统计
     * User: Administrator
     * Date: 2023/8/30
     * Time: 18:29
     * @return mixed
     * @throws \think\Exception
     */
    public function signs()
    {
        $where = $this->getMap('create_time');
        $map = $where['map'];
        $maps = $where['maps'];
        $usernumber = input('usernumber');

        $number = Member::count();
        if (!empty($usernumber)) {
            $maps['usernumber'] = $usernumber;
            $uid = Db('member')->where('usernumber', $usernumber)->value('uid');
            if ($uid) {
                $uids = Member::where('tuijianids', 'like', '%,' . $uid . ',%')->column('uid');
                $number = count($uids);
                array_unshift($uids, $uid);
                $map['uid'] = ['in', $uids];
            }
        }

        $total = Db('member_signin')->where($map)->count();

        $arr = [
            [
                'type' => 'input',
                'name' => 'usernumber',
                'inputid' => '',
                'readonly' => '',
                'title' => '会员账号',
                'value' => $usernumber,
            ]
        ];
        $this->searchCondition($maps, $arr);

        $this->assign('total_num', $number);
        $this->assign('total', $total);
        $this->assign('title', '签到统计');
        return $this->fetch();
    }

    /**
     * 升级列表
     * @return mixed
     */
    public function updateList()
    {
        $usernumber = input('usernumber');
        $type = input('type', 1);

        $maps = [
            'usernumber' => $usernumber,
            'type' => $type,
        ];

        $uid = 0;
        $map = [];
        if (!empty($usernumber)) {
            switch ($type) {
                case 1:
                    $uid = Member::where('usernumber', $usernumber)->value('uid');
                    break;
                case 2:
                    $uid = Member::where('realname', $usernumber)->value('uid');
                    break;
                case 3:
                    $uid = Member::where('mobile', $usernumber)->value('uid');
                    break;
            }
        }

        if ($uid > 0) {
            $map['uid'] = $uid;
        }

        $list = Db('member_update')->where($map)->order('id desc')->paginate(20, false, ['query' => $maps]);

        $page = $list->render();
        $list = $list->toArray();
        foreach ($list['data'] as &$v) {
            $v['usernumber'] = Member::where('uid', $v['uid'])->value('usernumber');
            $v['rank_name'] = \app\common\model\Levels::where('id', $v['rank'])->value('name');
            $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        $this->assign('_list', $list['data']);
        $this->assign('page', $page);

        /*追加查询条件*/
        $arr = array(
            array(
                'type' => 'select',
                'name' => 'type',
                'option' => array(
                    '1' => '会员账号',
                    '2' => '会员姓名',
                    '3' => '手机号码',
                ),
                'value' => $type,
                'inputid' => '',
                'readonly' => '',
            ),
            array(
                'type' => 'input',
                'name' => 'usernumber',
                'title' => '请输入会员账号等有效信息',
                'value' => $usernumber,
                'inputid' => '',
                'readonly' => '',
            ),

        );
        $this->searchCondition($maps, $arr);

        $this->assign('title', '升级申请列表');
        return $this->fetch();
    }

    /**
     * 升级处理
     */
    public function handleUpdate()
    {
        $status = input('status', 1);
        $id = input('id');
        $updateInfo = Db('member_update')->find($id);
        if (!$updateInfo) {
            $this->error('该申请不存在！');
        }
        if ($updateInfo['status'] != 0) {
            $this->error('该申请已处理！');
        }

        $res = Db('member_update')->where('id', $id)->update(['status' => $status]);
        if (!$res) {
            $this->error('处理失败');
        }
        if ($status == 1) {
            // 同意申请
            Member::where('uid', $updateInfo['uid'])->update(['userrank' => $updateInfo['rank']]);
            //更新贡献值每日释放数量
            Bonus::changeContributionRelease($uid);
        }

        $this->success('处理成功');
    }

    /**
     * 冻结或者解冻会员
     */
    public function freezestatus()
    {
        $id = input('id');
        $where1['uid'] = $where2['id'] = $id;
        $method = input('method');
        switch (strtolower($method)) {
            case 'freeze':
                $res1 = Db('member')->where($where1)->setField('status', -1);
                $res2 = Db('ucenter_member')->where($where2)->setField('status', -1);
                if ($res1 && $res2) {
                    $this->success('会员冻结成功');
                } else {
                    $this->error('会员冻结失败');
                }
                break;
            case 'unfreeze':
                $res1 = Db('member')->where($where1)->setField('status', 1);
                $res2 = Db('ucenter_member')->where($where2)->setField('status', 1);
                if ($res1 && $res2) {
                    $this->success('会员解冻成功');
                } else {
                    $this->error('会员解冻失败');
                }
                break;
            default:
                $this->error('参数非法');
        }
    }

    /**
     * 冻结或解冻提现
     */
    public function freezeWd()
    {
        $id = input('id');
        $isWd1 = input('is_wd1');
        $isWd2 = input('is_wd2');
        if ($isWd1) {
            $data['is_wd1'] = $isWd1;
        }
        if ($isWd2) {
            $data['is_wd2'] = $isWd2;
        }

        $res = Db('member')->where('uid', $id)->update($data);
        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 代理商恢复或取消分佣
     */
    public function freezeArea()
    {
        $id = input('id');
        $isArea = input('is_area');
        switch ($isArea) {
            case 1:
                $msg = '代理商恢复分佣';
                break;
            case -1:
                $msg = '代理商取消分佣';
                break;
        }
        $res = Db('member')->where('uid', $id)->setField('is_area', $isArea);
        if ($res) {
            $this->success($msg . '成功');
        } else {
            $this->error($msg . '失败');
        }
    }

    /**
     * 会员详细信息
     * @return mixed
     */
    public function uinfo()
    {
        $uid = input('id');
        $uinfo = Member::get($uid);
        /*地址转换*/
        $arr = explode(',', $uinfo->area);
        $area = '';
        foreach ($arr as $v) {
            $area .= Db('district')->where(array('id' => $v))->value('name');
        }

        $uinfo->start_sign_time = $uinfo->start_sign_time > 0 ? date('Y-m-d H:i:s', $uinfo->start_sign_time) : '未签到';
        $uinfo->end_sign_time = $uinfo->end_sign_time > 0 ? date('Y-m-d H:i:s', $uinfo->end_sign_time) : '未签到';

        $this->assign('area', $area);
        $this->assign('uinfo', $uinfo);
        $this->assign('title', $uinfo->realname . "的资料");
        return $this->fetch();
    }

    /**
     * 更新级别
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeLevel()
    {
        if (request()->isPost()) {
            $level = input('level');
            $uid = input('uid');
            $user = Db('member')->where('uid', $uid)->find();
            if (!$user) {
                $this->error('该会员不存在！');
            }
            $res = Db('member')->where('uid', $uid)->setField('level', $level);
            if ($res) {
                $this->success('更新成功！');
            } else {
                $this->error('更新失败！');
            }
        } else {
            $this->error('非法操作！');
        }
    }

    /**
     * 是否发货
     */
//    public function changeIsSend()
//    {
//        if (request()->isPost()) {
//            $isSend = input('isSend');
//            $uid = input('uid');
//            $user = Db('member')->where('uid', $uid)->find();
//            if (!$user) {
//                $this->error('该会员不存在！');
//            }
//
//            $res = Db('member')->where('uid', $uid)->setField('is_send', $isSend);
//            if ($res) {
//                $this->success('更新成功！');
//            } else {
//                $this->error('更新失败！');
//            }
//        } else {
//            $this->error('非法操作！');
//        }
//    }

    /**
     * 推荐结构树查询
     */
    public function tTree()
    {
        $uid = 1;
        if (request()->isPost()) {
            $usernumber = input('usernumber');
            $map['usernumber'] = $usernumber;
            $userinfo = Db('member')->where($map)->find();
            if (!$userinfo) {
                $this->error('会员不存在！');
            }
            $uid = $userinfo['uid'];
        }
        $this->assign('uid', 0);
        $this->assign('rootid', $uid);
        $this->assign('title', "推荐拓扑图");
        return $this->fetch('ttree');
    }

    /**
     * A网节点拓扑
     */
//    public function userImg()
//    {
//        $uid = input('uid', 1);
//        $p = input('p', 0);
//        $usernumber = input('usernumber', '');
//        if ($usernumber) {
//            $uid = Db('member')->where('usernumber', $usernumber)->value('uid');
//        }
//        $deep = 5;
//        $pdeep = Db('member')->field('pdeep')->where('uid', $uid)->find();
//        if (!isset($pdeep)) {
//            $this->error('会员信息不存在');
//        }
//        if ($p) {
//            $uid = Db('member')->where(array('uid' => $uid))->value('parentid');
//        }
//        $maxdeep = $pdeep['pdeep'] + $deep;
//        $html = $this->createImg($uid, $maxdeep);
//        $this->assign('html', $html);
//        $this->assign('usernumber', $usernumber);
//        $this->assign('uid', $uid);
//        $this->assign('title', "网络图谱");
//        return $this->fetch('userimg');
//    }

//    public function userImgB()
//    {
//        $uid = input('id', 1);
//        $p = input('p', 0);
//        $usernumber = input('usernumber', '');
//        if ($usernumber) {
//            $uid = Db('bmember')->where('usernumber', $usernumber)->value('id');
//        }
//        $deep = 4;
//        $pdeep = Db('bmember')->field('pdeep')->where('id', $uid)->find();
//        if (!isset($pdeep)) {
//            $this->error('会员信息不存在');
//        }
//        if ($p) {
//            $uid = Db('bmember')->where(array('id' => $uid))->value('parentid');
//        }
//        $maxdeep = $pdeep['pdeep'] + $deep;
//        $html = $this->createImg1($uid, $maxdeep);
//        $this->assign('html', $html);
//        $this->assign('usernumber', $usernumber);
//        $this->assign('uid', $uid);
//        $this->assign('title', "网络图谱");
//        return $this->fetch('userimgb');
//    }

    /**
     * 修改资料
     */
    public function updateInfo()
    {
        $uid = input('uid');

        $user = Db('member')->find($uid);
        if (request()->isPost()) {
            $data = input('post.');
//            $rule = [
//                'realname|会员姓名' => 'require',
//                'IDcard|身份证号' => 'length:18',
//                'mobile|联系方式' => 'require|length:11|number',
//                'banknumber|银行卡号' => 'require|number'
//            ];
//
//            $validate = new Validate($rule);
//            if (!$validate->check($data)) {
//                $this->error($validate->getError());
//            };

//            if ($data['usernumber']) {
//                $member = Db('member')->where('uid', 'neq', $uid)->where('usernumber', $data['usernumber'])->find();
//                if ($member) {
//                    $this->error('该账号已存在！');
//                }
//            }

//            $code = input('code');
//            if ($code != session('email_code')) {
//                $this->error('邮箱验证码错误');
//            }

            if ($data['password1']) {
                $data['psd1'] = $data['password1'];
            }
            if ($data['password2']) {
                $data['psd2'] = $data['password2'];
            }

            $province = $data['province'];
            $city = $data['city'];
            $district = $data['district'];
            if ($district > 0) {
                $area = $province . ',' . $city . ',' . $district;
                $data['area'] = $area;
            }

            unset($data['password1'], $data['password2'], $data['uid'], $data['province'], $data['city'], $data['district'], $data['code']);

            $User = new UserApi();
            $res = $User->updateUser($uid, $data);
            if (!$res) {
                $this->error('会员信息更新失败！');
            } else {
                session('email_code', null);

                $this->success('会员信息更新成功！', url('userIndex'));
            }
        } else {
            if (!self::$adminInfo['email']) {
                $this->error('缺少邮箱，不可编辑');
            }

            $area = '';
            if ($user['area']) {
                $arr = explode(',', $user['area']);
                foreach ($arr as $v) {
                    $area .= Db::name('district')->where('id', $v)->value('name');
                }
            }

            $ranks = config('URANK_NAME');
            $levels = config('LEVELS');

            $this->assign('email', self::$adminInfo['email']);
            $this->assign('ranks', $ranks);
            $this->assign('levels', $levels);
            $this->assign('area', $area);
            $this->assign('uinfo', $user);
            $this->assign('allow_bank', config('ALLOW_BANK'));
            $this->assign('title', '修改资料');
            return $this->fetch('updateinfo');
        }
    }

}